package com.github.mikephil.charting.stockChart.charts;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;

import androidx.core.content.ContextCompat;

import com.github.mikephil.charting.R;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.stockChart.dataManage.TimeDataManage;
import com.github.mikephil.charting.stockChart.markerView.LeftMarkerView;
import com.github.mikephil.charting.stockChart.markerView.TimeRightMarkerView;
import com.github.mikephil.charting.stockChart.model.TimeDataModel;
import com.github.mikephil.charting.stockChart.renderer.TimeLineChartRenderer;
import com.github.mikephil.charting.stockChart.renderer.TimeXAxisRenderer;
import com.github.mikephil.charting.utils.DataTimeUtil;
import com.github.mikephil.charting.utils.StrUtil;

import java.util.ArrayList;
import java.util.List;


public class TimeLineChart extends LineChart {
    private LeftMarkerView myMarkerViewLeft;
    private TimeRightMarkerView myMarkerViewRight;
    private TimeDataManage kTimeData;
    private VolSelected volSelected;


    protected Paint mAvgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    protected Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); //文字
    protected Paint mTextLeftPaint = new Paint(Paint.ANTI_ALIAS_FLAG); //左边文字
    protected Paint mTextReightPaint = new Paint(Paint.ANTI_ALIAS_FLAG);//右边文字
    protected Paint mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); //轴线
    protected Paint mTextBottomPaint = new Paint(Paint.ANTI_ALIAS_FLAG); //下边文字
    protected Paint mPricePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    protected Paint mPriceAveragePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    protected Paint mVolumePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    protected Paint mSelectorBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    protected Paint mSelectorTitlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    protected Paint mSelectorTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private float mTextSize = 10;
    private int selectedIndex;
    private long mCount = 0;

    public void setVolSelected(VolSelected volSelected) {
        this.volSelected = volSelected;
    }

    public interface VolSelected {
        void onVolSelected(int value);

        void onValuesSelected(double price, double upDown, int vol, double avg);
    }

    public TimeLineChart(Context context) {
        super(context);
        initData();
    }

    public TimeLineChart(Context context, AttributeSet attrs) {
        super(context, attrs);
        initData();
    }

    public TimeLineChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initData();
    }


    private void initData() {
        mTopPadding = dp2px(mTopPadding);
        mBottomPadding = dp2px(mBottomPadding);

        mTextSize = sp2px(mTextSize);

        mTextPaint.setColor(Color.parseColor("#6774FF"));
        mTextPaint.setTextSize(sp2px(11));
        mTextPaint.setStrokeWidth(dp2px(0.5f));

        /*mTextMACDPaint.setColor(Color.parseColor("#6774FF"));
        mTextMACDPaint.setTextSize(sp2px(10));
        mTextMACDPaint.setStrokeWidth(dp2px(0.5f));
*/
        mTextLeftPaint.setColor(Color.parseColor("#B1B2B6"));
        mTextLeftPaint.setTextSize(mTextSize);
        mTextLeftPaint.setStrokeWidth(dp2px(0.5f));

        mTextReightPaint.setColor(Color.parseColor("#B1B2B6"));
        mTextReightPaint.setTextSize(mTextSize);
        mTextReightPaint.setStrokeWidth(dp2px(0.5f));

        mTextBottomPaint.setColor(Color.parseColor("#6A798E"));
        mTextBottomPaint.setTextSize(mTextSize);
        mTextBottomPaint.setStrokeWidth(dp2px(0.5f));

        mLinePaint.setColor(Color.parseColor("#6774FF")); //轴线
        mLinePaint.setTextSize(mTextSize);
        mLinePaint.setStrokeWidth(dp2px(0.5f));

        mAvgPaint.setColor(Color.parseColor("#90A901"));
        mAvgPaint.setStrokeWidth(dp2px(0.5f));
        mAvgPaint.setTextSize(mTextSize);

        mPricePaint.setColor(Color.parseColor("#FF6600"));
        mPricePaint.setStrokeWidth(dp2px(0.5f));
        mPricePaint.setTextSize(mTextSize);

        mSelectorBackgroundPaint.setColor(Color.parseColor("#4F5490"));

        mSelectorTitlePaint.setColor(Color.parseColor("#9EB2CD"));
        mSelectorTitlePaint.setTextSize(sp2px(10));

        mSelectorTextPaint.setColor(Color.parseColor("#E7EDF5"));
        mSelectorTextPaint.setTextSize(sp2px(13));

        mPriceAveragePaint.setDither(true);
        mPriceAveragePaint.setColor(Color.parseColor("#FFEFD521"));
        mPriceAveragePaint.setStrokeWidth(dp2px(0.5f));

        mVolumePaint.setColor(ContextCompat.getColor(getContext(), R.color.chart_red));

    }

    @Override
    protected void calculateSelectedX(float x) {
        selectedIndex = (int) (x * 1f / getX(kTimeData.getDatas().size() - 1) * (kTimeData.getDatas().size() - 1));
        if (selectedIndex < 0) {
            selectedIndex = 0;
        }
        if (selectedIndex > kTimeData.getDatas().size() - 1) {
            selectedIndex = kTimeData.getDatas().size() - 1;
        }
    }

    @Override
    protected void initRenderer() {
        mRenderer = new TimeLineChartRenderer(this, mAnimator, mViewPortHandler);
    }

    @Override
    protected void initXAxisRenderer() {
        mXAxisRenderer = new TimeXAxisRenderer(mViewPortHandler, (TimeXAxis) mXAxis, mLeftAxisTransformer, this);
    }

    @Override
    public void initXAxis() {
        mXAxis = new TimeXAxis();
    }

    /*返回转型后的左右轴*/
    public void setMarker(LeftMarkerView markerLeft, TimeRightMarkerView markerRight, TimeDataManage kTimeData) {
        this.myMarkerViewLeft = markerLeft;
        this.myMarkerViewRight = markerRight;
        this.kTimeData = kTimeData;

        this.mPointCount = kTimeData.getDatas().size();
    }

    @Override
    protected void drawMarkers(Canvas canvas) {
        // if there is no marker view or drawing marker is disabled
        if (!isDrawMarkersEnabled() || !valuesToHighlight()) {
            return;
        }

        for (int i = 0; i < mIndicesToHighlight.length; i++) {

            Highlight highlight = mIndicesToHighlight[i];

            IDataSet set = mData.getDataSetByIndex(highlight.getDataSetIndex());

            Entry e = mData.getEntryForHighlight(mIndicesToHighlight[i]);
            int entryIndex = set.getEntryIndex(e);

            // make sure entry not null
            if (e == null || entryIndex > set.getEntryCount() * mAnimator.getPhaseX()) {
                continue;
            }

            float[] pos = getMarkerPosition(highlight);

            // check bounds
            if (!mViewPortHandler.isInBounds(pos[0], pos[1])) {
                continue;
            }

            float yValForXIndex1 = (float) kTimeData.getDatas().get((int) mIndicesToHighlight[i].getX()).getNowPrice();
            float yValForXIndex2 = (float) kTimeData.getDatas().get((int) mIndicesToHighlight[i].getX()).getPer();

            if (volSelected != null) {
                volSelected.onVolSelected(kTimeData.getDatas().get((int) mIndicesToHighlight[i].getX()).getVolume());
                volSelected.onValuesSelected(kTimeData.getDatas().get((int) mIndicesToHighlight[i].getX()).getNowPrice(),
                        kTimeData.getDatas().get((int) mIndicesToHighlight[i].getX()).getPer(),
                        kTimeData.getDatas().get((int) mIndicesToHighlight[i].getX()).getVolume(),
                        kTimeData.getDatas().get((int) mIndicesToHighlight[i].getX()).getAveragePrice());
            }

            myMarkerViewLeft.setData(yValForXIndex1);
            myMarkerViewRight.setData(yValForXIndex2);

            myMarkerViewLeft.refreshContent(e, mIndicesToHighlight[i]);
            myMarkerViewRight.refreshContent(e, mIndicesToHighlight[i]);
            /*修复bug*/
            // invalidate();
            /*重新计算大小*/
            myMarkerViewLeft.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            myMarkerViewLeft.layout(0, 0, myMarkerViewLeft.getMeasuredWidth(), myMarkerViewLeft.getMeasuredHeight());
            myMarkerViewRight.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            myMarkerViewRight.layout(0, 0, myMarkerViewRight.getMeasuredWidth(), myMarkerViewRight.getMeasuredHeight());

            if (getAxisLeft().getLabelPosition() == YAxis.YAxisLabelPosition.OUTSIDE_CHART) {
                myMarkerViewLeft.draw(canvas, mViewPortHandler.contentLeft() - myMarkerViewLeft.getWidth() / 2, pos[1] + myMarkerViewLeft.getHeight() / 2);
            } else {
                myMarkerViewLeft.draw(canvas, mViewPortHandler.contentLeft() + myMarkerViewLeft.getWidth() / 2, pos[1] + myMarkerViewLeft.getHeight() / 2);
            }
            if (getAxisRight().getLabelPosition() == YAxis.YAxisLabelPosition.OUTSIDE_CHART) {
                myMarkerViewRight.draw(canvas, mViewPortHandler.contentRight() + myMarkerViewRight.getWidth() / 2, pos[1] + myMarkerViewRight.getHeight() / 2);//- myMarkerViewRight.getWidth()
            } else {
                myMarkerViewRight.draw(canvas, mViewPortHandler.contentRight() - myMarkerViewRight.getWidth() / 2, pos[1] + myMarkerViewRight.getHeight() / 2);//- myMarkerViewRight.getWidth()
            }
            // callbacks to update the content
//            mMarker.refreshContent(e, highlight);

            // draw the marker
//            mMarker.draw(canvas, pos[0], pos[1]);


            TimeDataModel d = kTimeData.getDatas().get((int) mIndicesToHighlight[i].getX());
            drawMainSelector(selectedIndex, d, canvas);
        }

    }


    /**
     * draw选择器
     *
     * @param canvas
     */

    private void drawMainSelector(int selectedIndex, TimeDataModel point, Canvas canvas) {
        //绘制 MACD, DIFF, DEA, STICK 的指标
        /*if (isDrawChildView) {
            //GJL
            if (!isCJL) {
                drawMACDText(selectedIndex, point, canvas);
                invalidate();
            }
        }*/

        Paint.FontMetrics metrics = mTextLeftPaint.getFontMetrics();
        float textHeight = metrics.descent - metrics.ascent;

        float padding = dp2px(5);
        float margin = dp2px(5);
        float width = 0;
        float left = 5;
        float top = 10;
        float bottom = 10;

        List<String> strings = new ArrayList<>();
        String date = DataTimeUtil.secDateToTime(point.getTimeMills());
        strings.add(date);
//        strings.add("价格");
//        strings.add(point.getNowPrice() + "");
        strings.add("均价");
        strings.add(point.getAveragePrice() + "");

        //涨跌幅度=（现价-昨收价）/昨收价x100%  涨跌幅=(今日收盘价-昨日收盘价)/昨日收盘价*100%  （收盘价/开盘价-1）*100%，
//        strings.add("涨跌");
//        DecimalFormat mFormat = new DecimalFormat("#0.00%");
//        double percent = (point.getNowPrice() - point.getPreClose()) / point.getPreClose();
//        strings.add(mFormat.format(percent) + "");
//        strings.add(point.getUpdown() + "");
//        strings.add(point.getPercent() + "");

//        strings.add("持仓量");
//        strings.add(point.getInterest() + "");
//        strings.add(point.getChgInterest() + ""); //???

        strings.add("成交量");
        strings.add(point.getVolume() + "");
//        strings.add(point.getTotal() + "");
//        strings.add(point.getChgInterest() + "");

        for (int i = 0; i < strings.size(); i++) {
            width = Math.max(width, mSelectorTextPaint.measureText(strings.get(i)));
        }
        width = width + dp2px(6) * 2;

        float x = getX(selectedIndex);
        if (x > mWidth / 2) {
            left = margin;
        } else {
            left = mWidth - width - margin;
        }
        float height = top + padding * 2 + (textHeight - metrics.bottom - metrics.top) / 2 +
                (textHeight + padding) * (strings.size() - 1);
        RectF r = new RectF(left, top, left + width, top + height + bottom);
        canvas.drawRoundRect(r, padding, padding, mSelectorBackgroundPaint);

        float y = top + padding * 2 + (textHeight - metrics.bottom - metrics.top) / 2;

//        if (x > mWidth / 2) {
//            left = margin + padding;
//            mSelectorTextPaint.setTextAlign(Paint.Align.LEFT);
//            mSelectorTitlePaint.setTextAlign(Paint.Align.LEFT);
//        } else {
//            left = mWidth - margin - padding;
//            mSelectorTextPaint.setTextAlign(Paint.Align.RIGHT);
//            mSelectorTitlePaint.setTextAlign(Paint.Align.RIGHT);
//        }
        for (String s : strings) {
            if (StrUtil.isTimeText(s)) {
                mSelectorTextPaint.setColor(getResources().getColor(R.color.color_text_positive_paint));
                canvas.drawText(s, left + padding, y, mSelectorTextPaint);

            } else if (StrUtil.isChinaText(s)) {
                canvas.drawText(s, left + padding, y, mSelectorTitlePaint);

            } else {
                if (StrUtil.isPositiveOrNagativeNumberText(s)) {
                    mSelectorTextPaint.setColor(getResources().getColor(R.color.color_negative_value));
                    canvas.drawText(s, left + padding, y, mSelectorTextPaint);
                } else {
                    mSelectorTextPaint.setColor(getResources().getColor(R.color.color_text_positive_paint));
                    canvas.drawText(s, left + padding, y, mSelectorTextPaint);
                }
            }

            y += textHeight + padding;
        }

    }

    private float getX(int i) {
        return mBasePaddingLeft + mScaleX * i;
    }

    @Override
    protected void notifyChanged() {
        super.notifyChanged();

        //x轴的缩放值
        mScaleX = mBaseWidth / (mPointCount - 1);

    }

    //    public void setHighlightValue(Highlight h) {
//        if (mData == null)
//            mIndicesToHighlight = null;
//        else {
//            mIndicesToHighlight = new Highlight[]{h};
//        }
//        invalidate();
//    }

    //调换画数据和右轴数据的位置，防止label数据被覆盖
//    @Override
//    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);
//        if (mData == null)
//            return;
//        long starttime = System.currentTimeMillis();
//
//        mXAxisRenderer.calcXBounds(this, mXAxis.mAxisLabelModulus);
//        mRenderer.calcXBounds(this, mXAxis.mAxisLabelModulus);
//
//        // execute all drawing commands
//        drawGridBackground(canvas);
//
//        if (mAxisLeft.isEnabled())
//            mAxisRendererLeft.computeAxis(mAxisLeft.mAxisMinimum, mAxisLeft.mAxisMaximum);
//        if (mAxisRight.isEnabled())
//            mAxisRendererRight.computeAxis(mAxisRight.mAxisMinimum, mAxisRight.mAxisMaximum);
//
//        mXAxisRenderer.renderAxisLine(canvas);
//        mAxisRendererLeft.renderAxisLine(canvas);
//        mAxisRendererRight.renderAxisLine(canvas);
//
//        // make sure the graph values and grid cannot be drawn outside the
//        // content-rect
//        int clipRestoreCount = canvas.save();
//        canvas.clipRect(mViewPortHandler.getContentRect());
//
//        mXAxisRenderer.renderGridLines(canvas);
//        mAxisRendererLeft.renderGridLines(canvas);
//        mAxisRendererRight.renderGridLines(canvas);
//
//        if (mXAxis.isDrawLimitLinesBehindDataEnabled())
//            mXAxisRenderer.renderLimitLines(canvas);
//
//        if (mAxisLeft.isDrawLimitLinesBehindDataEnabled())
//            mAxisRendererLeft.renderLimitLines(canvas);
//
//        if (mAxisRight.isDrawLimitLinesBehindDataEnabled())
//            mAxisRendererRight.renderLimitLines(canvas);
//
//        //mRenderer.drawData(canvas);
//
//        // if highlighting is enabled
//        if (valuesToHighlight())
//            mRenderer.drawHighlighted(canvas, mIndicesToHighlight);
//
//        // Removes clipping rectangle
//        canvas.restoreToCount(clipRestoreCount);
//
//        mRenderer.drawExtras(canvas);
//
//        clipRestoreCount = canvas.save();
//        canvas.clipRect(mViewPortHandler.getContentRect());
//
//        if (!mXAxis.isDrawLimitLinesBehindDataEnabled())
//            mXAxisRenderer.renderLimitLines(canvas);
//
//        if (!mAxisLeft.isDrawLimitLinesBehindDataEnabled())
//            mAxisRendererLeft.renderLimitLines(canvas);
//
//        if (!mAxisRight.isDrawLimitLinesBehindDataEnabled())
//            mAxisRendererRight.renderLimitLines(canvas);
//
//        canvas.restoreToCount(clipRestoreCount);
//
//        mXAxisRenderer.renderAxisLabels(canvas);
//        mAxisRendererLeft.renderAxisLabels(canvas);
//        mAxisRendererRight.renderAxisLabels(canvas);
//
//        mRenderer.drawData(canvas);
//
//        mRenderer.drawValues(canvas);
//
//        mLegendRenderer.renderLegend(canvas);
//
//        drawMarkers(canvas);
//
//        drawDescription(canvas);
//    }


}
